package com.lzb.browser.adapter;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.lzb.browser.Content;
import com.lzb.browser.R;
import com.lzb.browser.bean.CollectBean;
import com.lzb.browser.dialog.AddAlbumDialog;
import com.lzb.browser.utils.AppSpUtils;
import com.lzb.browser.utils.IconDownloadTask;
import com.lzb.browser.utils.IconUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectDragAdapter extends RecyclerView.Adapter<CollectDragAdapter.ViewHolder> {
    private List<CollectBean> mDatas;
    private boolean isEdit;

    public CollectDragAdapter() {

    }

    public void setList(List<CollectBean> list) {
        this.mDatas = list;
        notifyDataSetChanged();
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_collect, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        // 加载图标
        loadIcon(holder.ivIcon, mDatas.get(position));

        holder.tvTitle.setText(mDatas.get(position).getTitle());
        holder.tvUrl.setText(mDatas.get(position).getUrl());
        if (isEdit) {
            holder.ivSel.setVisibility(View.VISIBLE);
            holder.ivEdit.setVisibility(View.VISIBLE);
            holder.ivSort.setVisibility(View.VISIBLE);
            if (mDatas.get(position).isSelected()) {
                holder.ivSel.setImageResource(R.drawable.select);
            } else {
                holder.ivSel.setImageResource(R.drawable.no_select);
            }
        } else {
            holder.ivSel.setVisibility(View.GONE);
            holder.ivEdit.setVisibility(View.GONE);
            holder.ivSort.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(view -> {
            if (isEdit) {
                mDatas.get(position).setSelected(!mDatas.get(position).isSelected());
                notifyItemChanged(position);
                if (listener != null) {
                    listener.clickItem(position, mDatas.get(position).isSelected());
                }
            } else {
                if (listener != null) {
                    listener.click(position);
                }
            }
        });

        holder.ivEdit.setOnClickListener(view -> {
            if (listener != null) {
                listener.clickEdit(position);
            }
        });

    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    // 拖动排序逻辑
    public void onItemMove(int fromPos, int toPos) {
        Collections.swap(mDatas, fromPos, toPos);
        List<CollectBean> listSave = new ArrayList<>();
        listSave.addAll(mDatas);
        for (CollectBean collectBean : listSave) {
            collectBean.setSelected(false);
        }
        AppSpUtils.saveCollectList(listSave);
        notifyItemMoved(fromPos, toPos);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivIcon, ivSel, ivEdit, ivSort;
        TextView tvTitle, tvUrl;

        ViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvCollectItemTitle);
            tvUrl = itemView.findViewById(R.id.tvCollectItemUrl);
            ivIcon = itemView.findViewById(R.id.ivCollectItemIcon);
            ivSel = itemView.findViewById(R.id.ivCollectItemSel);
            ivEdit = itemView.findViewById(R.id.ivCollectItemEdit);
            ivSort = itemView.findViewById(R.id.ivCollectItemSort);
        }
    }

    /**
     * 加载图标
     */
    private void loadIcon(ImageView ivIcon, CollectBean item) {
        // 优先使用保存的图标数据
        if (!TextUtils.isEmpty(item.getIconData())) {
            Bitmap iconBitmap = IconUtils.base64ToBitmap(item.getIconData());
            if (iconBitmap != null) {
                ivIcon.setImageBitmap(iconBitmap);
                return;
            }
        }

        if (!TextUtils.isEmpty(item.getIconUrl())) {
            // 使用图标URL加载，同时下载并保存
            RequestOptions options = new RequestOptions()
                    .error(R.drawable.bd)
                    .placeholder(R.drawable.bd)
                    .transform(new RoundedCorners(8));

            Glide.with(Utils.getApp())
                    .load(item.getIconUrl())
                    .apply(options)
                    .into(ivIcon);

            // 异步下载图标并保存
            downloadAndSaveIcon(item);
        } else {
            // 加载默认图标
            loadDefaultIcon(ivIcon, item.getUrl());
        }
    }

    /**
     * 下载并保存图标
     */
    private void downloadAndSaveIcon(CollectBean item) {
        new IconDownloadTask(Utils.getApp(), new IconDownloadTask.OnIconDownloadListener() {
            @Override
            public void onIconDownloaded(Bitmap bitmap, String iconUrl) {
                // 将图标转换为Base64
                String iconData = IconUtils.bitmapToBase64(bitmap);
                if (iconData != null) {
                    item.setIconData(iconData);
                    // 通知数据更新
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onIconDownloadFailed(String iconUrl) {
                // 图标下载失败，保持默认图标
            }
        }).execute(item.getIconUrl());
    }

    private void loadDefaultIcon(ImageView imageView, String url) {
        // 生成网站的首字母作为默认图标
        String domain = extractDomain(url);
        String firstChar = domain.isEmpty() ? "W" : domain.substring(0, 1).toUpperCase();

        // 这里可以创建一个带有首字母的默认图标
        // 暂时使用默认的网页图标
        imageView.setImageResource(R.drawable.bd);
    }

    private String extractDomain(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        try {
            // 简单的域名提取逻辑
            String domain = url.replace("https://", "")
                    .replace("http://", "")
                    .replace("www.", "");

            int slashIndex = domain.indexOf("/");
            if (slashIndex != -1) {
                domain = domain.substring(0, slashIndex);
            }

            return domain;
        } catch (Exception e) {
            return "";
        }
    }

    private Ilistener listener;

    public void setListener(Ilistener listener) {
        this.listener = listener;
    }

    public interface Ilistener {
        void clickItem(int pos, boolean isSelected);

        void click(int pos);

        void clickEdit(int pos);
    }

}
